package covertjava.intercept;

/**
 * <p>Specifies a listener interface for incoming messages</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */

import covertjava.chat.*;
import java.lang.reflect.*;


public class TracingProxy  implements InvocationHandler {

    protected Object target;

    public TracingProxy(Object target) {
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result;
        try {
            System.out.println("Entering " + method.getName());
            result = method.invoke(target, args);
        }
        catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
        finally {
            System.out.println("Leaving " + method.getName());
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        ChatServer chatServer = ChatServer.getInstance();
        chatServer.setMessageListener(new MainFrame(false));

        TracingProxy listener = new TracingProxy(chatServer.getMessageListener());
        Object proxy = Proxy.newProxyInstance(
            chatServer.getClass().getClassLoader(),
            new Class[] {MessageListener.class},
            listener
            );
        chatServer.setMessageListener((MessageListener)proxy);
        MessageInfo messageInfo = new MessageInfo("localhost", "alex");
        chatServer.receiveMessage("Test message", messageInfo);
        System.exit(0);
    }
}
